import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    email: '',
    phone: ''
  },

  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onConfirmPasswordInput(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  onEmailInput(e) {
    this.setData({
      email: e.detail.value
    });
  },

  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    });
  },

  onRegister() {
    if (!this.data.username) {
      wx.showToast({
        title: '请输入用户名',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }
    
    // 调用注册接口
    post(apiPaths.register, {
      username: this.data.username,
      password: this.data.password,
      nickname: this.data.nickname,
      email: this.data.email,
      phone: this.data.phone
    }).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });
        
        // 注册成功后返回登录页面
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '注册失败',
        icon: 'none'
      });
    });
  },

  onCancel() {
    wx.navigateBack();
  }
});